package controllers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/logs"
	"public_security/models"
	"public_security/plugins"
)

type ControllerInterface interface {
	beego.ControllerInterface
}

type BaseController struct {
	beego.Controller
	LoginUser *models.Users
}

func (i *BaseController) Prepare() {
	i.BasePrepare()
}
func (i *BaseController) GetCtx() *context.Context {
	return i.Ctx
}

// 通用controller实例fork后执行的准备工作
func (i *BaseController) BasePrepare() {
	loginUser := i.Ctx.Input.GetData(models.CtxLoginUser)
	if loginUser != nil {
		i.SetLoginUser(loginUser.(*models.Users))
	}
}

// 获取当前登陆用户
func (i *BaseController) GetLogEdUser() interface{} {
	return i.Ctx.Input.GetData(models.CtxLoginUser)
}

// 设置当前登陆用户
func (i *BaseController) SetLoginUser(user *models.Users) {
	i.LoginUser = user
}

// 通用消息输出
func (i *BaseController) ToMessage(state string, data interface{}, message string, others ...map[string]interface{}) map[string]interface{} {
	r := map[string]interface{}{
		"state":   state,
		"data":    data,
		"message": message,
	}
	for _, other := range others {
		for k, v := range other {
			r[k] = v
		}
	}
	i.Data["json"] = r
	i.ServeJSON(false)
	if state == "success" {
		logs.Info("URL【%s】的返回结果为>>>>>>>>RESULT 【code = %v,message = %s】", i.Ctx.Request.URL, state, message)
	} else if state == "failed" {
		logs.Error("URL【%s】的返回结果为>>>>>>>>RESULT 【code = %v,message = %s】", i.Ctx.Request.URL, state, message)
	} else {
		logs.Debug("URL【%s】的返回结果为>>>>>>>>RESULT 【code = %v,message = %s】", i.Ctx.Request.URL, state, message)
	}
	return r
}

// 返回成功消息
func (i *BaseController) ToMessageSuccess(data interface{}, message string, others ...map[string]interface{}) map[string]interface{} {
	return i.ToMessage("success", data, message, others...)
}

// 返回成功消息
func (i *BaseController) ZyToMessage(code uint, msg string, data interface{}) map[string]interface{} {
	ret := make(map[string]interface{})
	ret["code"] = code
	ret["msg"] = msg
	ret["data"] = data

	i.Data["json"] = ret
	i.ServeJSON(true)
	logs.Info("URL【%s】的返回结果为>>>>>>>>RESULT 【code = %v,message = %s】", i.Ctx.Request.URL, code, msg)
	return ret
}

//返回状态status和消息message
func (i *BaseController) ToStatusAndMessage(state bool, message string) map[string]interface{} {
	status := 0
	if !state {
		status = 1
	}
	r := map[string]interface{}{
		"resultCode": status,
		"resultDes":  message,
	}
	i.Data["json"] = r
	i.ServeJSON(true)
	logs.Debug("URL【%s】的返回结果为>>>>>>>>RESULT 【code = %v,message = %s】", i.Ctx.Request.URL, status, message)
	return r
}

// 失败消息返回
func (i *BaseController) ToMessageFailed(data interface{}, message string, others ...map[string]interface{}) map[string]interface{} {
	return i.ToMessage("failed", data, message, others...)
}
func (i *BaseController) RequestJsonScan(object interface{}) error {
	return plugins.CtxToJson(i.Ctx, object)
}
